import React, {useEffect, useRef, useState} from 'react';
import {Button, Empty, message} from "antd";
import classes from './index.module.scss'
import {ReactEmojiEditor} from 'react-emotor'
import Comment from "./Comment";
import {useDispatch, useSelector} from "react-redux";
import {useParams} from "react-router-dom";
import {reqPublishComment} from "../../../api/frontDesk/frontDeskApi";
import {getCommentList} from "../../../store/frontDesk/commentSlice";
import {getToken} from "../../../utils/token";


const CommentList = (props) => {
    const emotor = useRef();

    const params = useParams()

    const {userAllInfo} = useSelector(state => state.persistedReducer.user)
    const [content, setContent] = useState('')

    const dispatch = useDispatch()

    // 组件内容改变回调函数
    const contentOnChange = async (content) => {
        setContent(content)
    }


    // 清空组件内容
    function clean() {
        emotor.current.clean();
    }

    // 组件获取焦点
    const publishComment = async () => {
        if (getToken()) {
            if (content !== '') {
                const result = await reqPublishComment({article_id: params.id, user_id: userAllInfo.id, content})
                if (result.status === 0) {
                    const getData = async () => {
                        dispatch(getCommentList(params.id))
                    }
                    getData()
                    message.success('发布评论成功')
                    emotor.current.clean();
                }
            }else {
                message.info('请不要发表空的评论')
            }
        } else {
            message.info('请先登录')
        }
    }


    return (
        <div className={classes.CommentListContainer}>
            <div  className={classes.Publish}>
                <ReactEmojiEditor
                    ref={emotor}
                    id="myEmotor"
                    placeholder='请遵守互联网法律和规范进行发言,点击发表评论即可发布'
                    onChange={content => contentOnChange(content)}
                />
                <div className={classes.actionBtn}>
                    <Button type="primary" onClick={clean}>清空</Button>
                    <Button type="primary" onClick={publishComment}>发表评论</Button>
                </div>
            </div>
            <div className={classes.CommentList}>
                {
                    props.commentList.length === 0 ?
                        <Empty description="暂无评论"></Empty> :
                        props.commentList.map((item, index) =>
                            <Comment users={props.users} key={item.id} comment={item}/>
                        )
                }
            </div>
        </div>
    );
};

export default CommentList;